// pages/overview/overview.js
Page({
  data: {
    matches: [],
    page: 0,
    pageSize: 10,
    hasMore: true
  },

  onLoad() {
    this.loadMatches();
  },

  loadMatches() {
    if (!this.data.hasMore) return;

    const db = wx.cloud.database();
    const { page, pageSize } = this.data;

    db.collection('match')
      .skip(page * pageSize)
      .limit(pageSize)
      .get()
      .then(res => {
        const newMatches = res.data.map(match => ({
          ...match,
          beginTime: match.beginTime ? this.formatDate(match.beginTime) : '未开赛',
          scores: []
        }));

        const promises = newMatches.map(match => {
          return db.collection('finalScore').where({
            matchid: match._id
          }).get().then(scoreRes => {
            match.scores = scoreRes.data;
          });
        });

        Promise.all(promises).then(() => {
          this.setData({
            matches: this.data.matches.concat(newMatches),
            page: page + 1,
            hasMore: newMatches.length === pageSize
          });
          this.loadGroups();
        });
      })
      .catch(err => {
        console.error("获取比赛数据失败:", err);
      });
  },

  loadGroups() {
    const db = wx.cloud.database();
    db.collection('group').get().then(res => {
      const groups = res.data;
      const matches = this.data.matches.map(match => {
        match.scores.forEach(score => {
          const group = groups.find(g => g.zuyuan.includes(score.username));
          score.groupName = group ? group.groupname : '无所属小组';
        });
        return match;
      });
      this.setData({ matches });
    }).catch(err => {
      console.error("获取小组数据失败:", err);
    });
  },

  formatDate(date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    const hours = d.getHours().toString().padStart(2, '0');
    const minutes = d.getMinutes().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  onReachBottom() {
    this.loadMatches();
  },
  // 结束比赛
  endMatch(e) {
    const matchId = e.currentTarget.dataset.id;
    const db = wx.cloud.database();

    db.collection('match').doc(matchId).update({
      data: {
        beginTime: db.command.remove()
      }
    }).then(() => {
      wx.showToast({
        title: '比赛已结束',
        icon: 'success'
      });
      this.setData({
        matches: this.data.matches.map(match => {
          if (match._id === matchId) {
            match.beginTime = '未开赛';
          }
          return match;
        })
      });
    }).catch(err => {
      console.error("结束比赛失败:", err);
      wx.showToast({
        title: '结束比赛失败',
        icon: 'none'
      });
    });
  },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})